<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Cache;

class CheckClientAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->header('clientKey') != env('APP_KEY')) {
            $clientIp = $request->getClientIp();
            $counter  = (int)Cache::get($clientIp);
            if ($counter) {
                Cache::increment($clientIp);
                if ($counter > 4) {
                    Cache::set($clientIp,$counter,3600 * $counter);
                    $later = $counter* 60;
                    throw new \Error('客户端错误' . $later . '小时后再来吧');
                }
            } else {
                Cache::set($clientIp,1,3600);
            }


            throw new \Error('客户端错误');
        }
        return $next($request);
    }
}
